package
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.net.LocalConnection;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import models.vo.UserVO;
	
	import org.dexter.sendDexterEvent;
	
	import vo.FlashVarsVO;
	
	public class WhiteBoardCtrl extends URLLoader
	{
		[DexterBinding]
		public var stratus:Stratus;
		[DexterBinding]
		public var flashVars:FlashVarsVO;
		private var lc:LocalConnection = new LocalConnection();
		private var datas:Array;
		private var currentPage:int;
		public function WhiteBoardCtrl()
		{
			super();
			lc.connect("wbhost");
			lc.client = this;
			addEventListener(Event.COMPLETE,onData);
		}
		[DexterEvent]
		public function initWhiteBoard(array:Array,c:int):void{
			datas = array;
			currentPage = c;
		}
		public function onData(event:Event):void{
			isLoading = false;
			if(requestList.length){
				load(requestList.shift());
			}
		}
		public function wbConnect():void{
			lc.send("whiteboard","admin",UserVO.self.role == UserVO.ADMIN||UserVO.self.role == UserVO.GUEST);
			lc.send("whiteboard","initPage",datas[currentPage]);
		}
		public function wbPaint(data:Object):void{
			var request:URLRequest = new URLRequest(flashVars.keepPage);
			var variables:URLVariables = new URLVariables();
			variables.ops = "whiteBoard";
			for(var i:String in data){
				if(typeof(data[i]) == "object"){
					variables[i] = JSON.encode(data[i]);
				}else
					variables[i] = data[i];
			}
			variables.t = Math.random();
			request.data = variables;
			request.method = URLRequestMethod.POST;
			load(request);
			sendDexterEvent("broadcast","wbPaint",data);
		}
		[DexterEvent]
		public function $wbPaint(data:Object):void{
			lc.send("whiteboard","wbPaint",data);
		}
		private var requestList:Vector.<URLRequest> = new Vector.<URLRequest>();
		private var isLoading:Boolean;
		override public function load(request:URLRequest):void{
			if(isLoading){
				requestList.push(request);
			}else{
				super.load(request);
				isLoading = true;
			}
		}
	}
}